<template>
  <el-card
      class="box-card"
      shadow="hover"
  >
    <Toolbar
        ref="bar"
        :databases="databases"
        :doing="doing"
        @query="execSql"
    />
    <SqlEditor ref="editor"/>
    <QueryResult ref="result"/>
  </el-card>
</template>
<script>
import Toolbar from "./components/Toolbar";
import SqlEditor from "./components/SqlEditor";
import QueryResult from "./components/QueryResult";
import {databaseInstanceListApi} from "@/api/manage";
import {execQueryApi} from "@/api/database";

export default {
  props: {
    appName: [String],
  },
  data() {
    return {databases: [], doing: false};
  },
  components: {Toolbar, SqlEditor, QueryResult},
  watch: {
    appName() {
      this.loadDatabases();
    }
  },
  methods: {
    async execSql(databaseId) {
      this.doing = true;
      if (databaseId == null) {
        this.$message.error("请选择数据库！");
        this.doing = false;
        return;
      }
      let sqlStr = this.$refs.editor.getEditorSelectText();
      if (sqlStr == null || sqlStr.length == 0) {
        this.doing = false;
        return;
      }
      let sqls = this.parseSql(sqlStr);
      this.$refs.result.results = [];
      try {
        for (let i = 0; i < sqls.length; i++) {
          let sql = sqls[i];
          let r = await execQueryApi(databaseId, sql);
          console.log(r);
          this.$refs.result.records.push({
            databaseId: databaseId,
            sql: sql,
            success: r.success,
            message: r.message,
            cost: r.cost,
            size: r.dataList != null ? r.dataList.length : 0,
          });
          this.$refs.result.results.push(r);
        }
        this.$refs.result.resultTabSelected = "record1";
      } catch (e) {
        console.log(e);
      }
      this.doing = false;
    },
    parseSql(sqlStr) {
      return sqlStr
          .replace(/#.*\n/g, "")
          .replace(/--.*\n/g, "")
          .replace(/\/\*.*\*\//g, "")
          .replace(/\n/g, " ")
          .split(";")
          .map((s) => s.trim())
          .filter((s) => s.length > 0);
    },
    async loadDatabases() {
      if (!this.appName) return;
      this.databases = await databaseInstanceListApi(this.appName);
    },
  },
  created() {
    this.loadDatabases();
  },
};
</script>
    